package com.mubai.web.controller.api;

import com.mubai.common.base.Return;
import com.mubai.system.domain.SysUser;
import com.mubai.system.service.SysUserService;
import com.mubai.web.core.base.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.WebAsyncTask;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;

/**
 * @author baichuanping
 * @create 2019-01-09
 */
@RestController
@RequestMapping("/open/test")
@Api(value="Open测试接口", description="开放API测试接口")
public class OpenTestController extends BaseController {
	@Autowired
	@Qualifier("taskExecutor")
	private ThreadPoolTaskExecutor taskExecutor;

	@Autowired
	private SysUserService sysUserService;

	@GetMapping(value = "/test")
	@ApiOperation(value="测试Callable", notes="测试 Callable; Callable类型 swagger 不能使用try,故实际开发建议使用 WebAsyncTask ,后者也是要强大的多")
	public Callable test(){
		System.out.println(new Date());
		return ()->{
			return success();
		};
	}

	@PostMapping(value = "/test2")
	@ApiOperation(value = "测试WebAsyncTask", notes = "测试WebAsyncTask")
	public WebAsyncTask test2(HttpServletRequest request) {
		System.out.println(String.format("异步工作线程: %s", Thread.currentThread().getName()));

		// 任务处理时间5s,不超时
		WebAsyncTask<Return> asyncTask = new WebAsyncTask<>(10 * 1000L, taskExecutor, () -> {
			List<SysUser> userList = new ArrayList<SysUser>();
			sysUserService.selectUserList(new SysUser()).forEach(System.out::println);
			return success();
		});
		// 任务执行完成时调用该方法
		asyncTask.onCompletion(() -> System.out.println("任务执行完成"));
		asyncTask.onTimeout(() -> {
			System.out.println("任务执行超时");
			return error();
		});
		System.out.println("继续处理其他事情");
		return asyncTask;
	}


	@PostMapping(value = "/test3")
	@ApiOperation(value="测试body", notes="测试body")
	public WebAsyncTask test3(HttpServletRequest request, @RequestBody String bodyData){
		WebAsyncTask test2 = new WebAsyncTask( () -> {
			String test = request.getParameter("test");
			System.out.println("dddddddddd");
			return bodyData;
		});
		return test2;
	}
	@PostMapping(value = "/test4")
	@ApiOperation(value="测试beanBody", notes="测试beanBody")
	public WebAsyncTask test4(HttpServletRequest request,@RequestBody SysUser SysUser){
		WebAsyncTask test2 = new WebAsyncTask( () -> {
			return SysUser;
		});
		return test2;
	}
	@PostMapping(value = "/test5")
	@ApiOperation(value="测试bean", notes="测试bean")
	public WebAsyncTask test5(HttpServletRequest request, SysUser SysUser){
		WebAsyncTask test2 = new WebAsyncTask( () -> {
			return SysUser;
		});
		return test2;
	}
}
